 Ext.namespace("MyApp.views.login").login_form = new function() {
  var pageId = 'MyApp.views.login.login_form';
  
  var formPanel;
  
  function addInstance() {
    if(MyApp.views.viewport.getComponent(pageId) == null) {
      MyApp.views.viewport.add(getInstance());
    }
  };
  
  function prepareOptions(options, defaultOptions) {
    options = options?options:new Object();
    Ext.applyIf(options, defaultOptions);
    
    return options;
  }
  
  function display(options) {
    var defaultOptions = {
      animation: {
        type: 'fade'
      }
    };
    
    options = prepareOptions(options, defaultOptions);
    
    MyApp.common.login.refreshLoginData(
        function() {
          if(MyApp.common.login.getLoginData().loggedIn == true) {
            MyApp.views.list_rows.list_rows_table.display({ animation: {
              type: 'slide',
              reveal: true,
              direction: 'down'
            }});
          } else {
            addInstance();
            
            formPanel.reset();
            MyApp.views.viewport.setActiveItem(pageId, options.animation);            
          }
        }
      );
  }
  this.display = display;
  
  function getInstance() {
    function doSubmit(formPanel) {
      MyApp.common.handleFormSubmit(restPath + '/login/login-form-data', null,
        function() {
          MyApp.common.login.refreshLoginData(function() {
            MyApp.views.list_rows.list_rows_table.display({ animation: {
              type: 'slide',
              reveal: true,
              direction: 'down'
            }});
          });
        }
      )(formPanel);
    }
  
    var toolbar = new Ext.Toolbar({
      dock : 'top',
      title: 'A Generic Touch App',
      items: [
        {xtype: 'spacer'}, 
        {
          text: 'Log in',
          listeners: {
            tap: function() {
              doSubmit(formPanel);
            }
          }
        }
      ]
    });
    
    formPanel = new Ext.form.FormPanel({
      items: [{
        xtype: 'fieldset',
        title: 'Log in',
        instructions: 'Test/testpw works in this demo.',
        items: [{
          xtype: 'textfield',
          label: 'Username',
          name: 'username',
          id: 'username',
          allowBlank: false
        },{
          xtype: 'passwordfield',
          label: 'Password',
          name: 'password',
          id: 'password',
          allowBlank: false
        }]
      }],
      
      listeners: {
        action: function(component, values, options){
          doSubmit(component.ownerCt.ownerCt);
        }
      }
    });
    
    return new Ext.Panel({
      id: pageId,
      layout: 'fit',
      
      dockedItems: [toolbar],
      items: [formPanel]
    });
  }
}();